﻿<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>从一个下拉列表往另一个下拉列表添加内容</title>
    <script type="text/javascript" language="JavaScript">


    </script>
</head>
<body>

<select id="oldSelect" name="love1" size="10" multiple>
    <option value="travl">旅游</option>
    <option value="NBA">NBA体育</option>
    <option value="study">学习</option>
    <option value="music">音乐</option>
    <option value="library">图书馆</option>
    <option value="bookshop">新华书店</option>
    <option value="shopping">逛街购物</option>
</select>
<input type="button" id="btnMove" value=">>>>">
<select id="newSelect" name="love2" size="10" multiple>
</select>

</body>

<script type="text/javascript" language="JavaScript">
    //设计字符对象的trimEnd方法
    String.prototype.trimEnd = function(trimString) {
        var re = new RegExp(trimString+"*$", "g");
        return this.replace(re, "");
    };
    //设计数组对象的indexof方法
    Array.prototype.indexOf = function(itemValue) {
        var nIndex = -1;
        for (var i=0; i<this.length; i++)
        {
            if (this[i] == itemValue) nIndex = i;
        }
        return nIndex;
    };
    //定义变量－变量为当前文档中的控件对象
    var oSrc = document.getElementById("oldSelect");
    var oTarget = document.getElementById("newSelect");
    var oCopy = document.getElementById("btnMove");
    //定义按钮的click事件
    oCopy.onclick = function() {
        var aSelectedIndexes = getSelectedIndexes(oSrc);
        for (var i=0; i<aSelectedIndexes.length; i++)
        {
            var oOption = document.createElement("OPTION");
            oOption.text = oSrc.options[aSelectedIndexes[i]].text;
            oOption.value = oSrc.options[aSelectedIndexes[i]].value;
            oTarget.options.add(oOption);
        }
    };
    //获取源下拉列表中被选择的内容
    function getSelectedIndexes(oSrc)
    {
        var aSelectedIndexes = new Array();

        for (var i=0; i<oSrc.options.length; i++)
        {
            if (oSrc.options[i].selected)
                aSelectedIndexes[aSelectedIndexes.length] = i;
        }

        return aSelectedIndexes;
    }
    //单击源下拉列表的事件
    oSrc.onclick = function() {
        this.selectedIndexes = getSelectedIndexes(this);
        if (this.selectedIndexes.length == 1)
            this.options[this.selectedIndexes].selected = false;
    };
    //改变源下拉列表选择的事件
    oSrc.onchange = function() {
        var j = this.selectedIndexes.indexOf(this.selectedIndex);
        if (j > -1)
        {
            this.options[this.selectedIndex].selected = false;
            this.selectedIndexes.splice(j, 1);
        }
        if (this.selectedIndexes.length > 0)
        {
            var nSelectedIndex;
            for (var i=0; i<this.selectedIndexes.length; i++)
            {
                nSelectedIndex = parseInt(this.selectedIndexes[i]);
                this.options[nSelectedIndex].selected = true;
            }
        }
    };

</script>

</html>